<?php

namespace App\Http\Controllers\Guard\Shop;

use App\Http\Controllers\Common\GuardController;
use App\Models\Shop\Goods\GoodsClassify;
use App\Models\Shop\Goods\GoodsSku;
use App\Models\Shop\Goods\GoodsSpu;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class GoodsSpuController extends GuardController {

    public function lst(Request $request) {
        $conditions = $request->input();

        if(!empty($conditions['selectClassifyId']) && count($conditions['selectClassifyId'])>0){
            $conditions['selectClassifyId'] = array_pop($conditions['selectClassifyId']);
        }

        $page = $request->input('page',1);
        $pageSize = $request->input('pageSize',20);
        $records = (new GoodsSpu())->getLst($conditions)->with(['getClassify:id,name','getBrand:id,name'])->paginate($pageSize,['*'],'page',$page);

        foreach ($records as $record) {
            $record->desc_detail = Str::limit($record->desc_detail,30);
        }

        return responseSuccess($records->items(),$records->total());
    }

    public function add(Request $request) {
        //dd($request->input());
        $spuInfo = $request->input('spuInfo',[]);
        $selectClassifyId = $request->input('selectClassifyId',[]);
        $this->validate($request, [
            'spuInfo.name'=>'required',
            'spuInfo.brand_id'=>'required|integer|gte:0',
            'spuInfo.desc_detail'=>'required',
            'spuInfo.cover_urls'=>'required|array|min:1',
        ],[],[
            'spuInfo.name'=>'商品名称',
            'spuInfo.brand_id'=>'品牌id',
            'spuInfo.desc_detail'=>'商品详情',
            'spuInfo.cover_urls'=>'商品封面',
        ]);

        $classify_id = is_array($selectClassifyId)?array_pop($selectClassifyId)??0:$selectClassifyId;

        $info = [
            'name'=>$spuInfo['name'],
            'classify_id'=>$classify_id,
            'brand_id'=>$spuInfo['brand_id'],
            'desc_detail'=>$spuInfo['desc_detail'],
            'cover_urls'=>implode(',', array_column($spuInfo['cover_urls'], 'filePath')),
            'is_single'=>$spuInfo['is_single'],
            'comment_count'=>$spuInfo['comment_count'],
            'sale_count'=>$spuInfo['sale_count'],
        ];

        try {
            DB::beginTransaction();

            //单规格
            if($spuInfo['is_single']==1){
                $spu = GoodsSpu::updateOrCreate(['id'=>$spuInfo['id']??0],$info);
                $skuInfo = [
                    'classify_last_id'=>$classify_id,
                    'spu_id'=>$spu->id,
                    'name'=>$info['name'],
                    'sub_title'=>$info['name'],
                    'stock'=>$spuInfo['stock'],
                    'market_price'=>$spuInfo['market_price'],
                    'cost_price'=>$spuInfo['cost_price'],
                    'price'=>$spuInfo['price'],
                ];
                GoodsSku::updateOrCreate(['id'=>$spuInfo['sku_id']??0],$skuInfo);
            } else{
                $skuInfo = $request->input('skuInfo',[]);
                $spu = GoodsSpu::updateOrCreate(['id'=>$spuInfo['id']??0],$info);
                if(count($skuInfo)>0){
                    foreach ($skuInfo as &$item) {
                        $item['classify_last_id'] = $classify_id;
                        $item['spu_id'] = $spu->id;
                        $item['updated_at'] = $item['created_at'] = date('Y-m-d H:i:s');
                        GoodsSku::updateOrCreate(['id'=>$item['id']??0],$item);
                    }

                }
            }
            DB::commit();
            return responseSuccess();
        }catch (\Exception $e){
            DB::rollBack();
            $tip = $e->getFile().':'.$e->getLine().':'.$e->getMessage();
            return responseFail($tip);
        }



    }

    public function changeStatus(Request $request) {
        $id = $request->input('id',0);
        $status = $request->input('status',1);
        $this->changeColById(GoodsSpu::class, $id, compact('status'));
        return responseSuccess();
    }

    public function detail(Request $request) {
        $id = $request->input('id',0);
        $record = GoodsSpu::where(compact('id'))->with('getSku')->first();
        $imgs = array_filter(explode(',', $record->cover_urls));
        $temp = [];
        foreach ($imgs as $img){
            $temp[] = [
                'uid'=>uniqid(),
                'filePath'=>$img,
                'url'=>asset($img)
            ];
        }
        $record->cover_urls = $temp;
        $classify = GoodsClassify::find($record->classify_id);
        $grandFatherClassify = GoodsClassify::find($classify->pid)->id??0;
        $temp =[];
        if($grandFatherClassify!=0)
            $temp[] = $grandFatherClassify;
        if($classify->pid!=0)
            $temp[] = $classify->pid;
        if($classify->id!=0)
            $temp[] = $classify->id;

        $record->all_classify_ids = array_unique($temp);
        return responseSuccess($record->toArray());

    }

}
